package com.bible.test.common.activity.webview;

import java.io.File;

import com.bible.fire.R;
import com.bible.fire.api.wps.DocSaveReceiver;
import com.bible.fire.api.wps.WPSAssistant;
import com.bible.fire.util.PackageUtil;
import com.bible.fire.util.SystemConstant;
import com.bible.fire.util.file.DownloadAsynTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MyBrowser extends Activity {
	
	private String TAG = MyBrowser.class.getSimpleName();
	
	private ProgressDialog pd;
	
	private DocSaveReceiver dsReceiver = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_PROGRESS);//用title bar做进度条
		setContentView(R.layout.mybrowser);
		final WebView webView=(WebView)findViewById(R.id.browser);
		final EditText text=(EditText)findViewById(R.id.url);
		Button go=(Button)findViewById(R.id.go);
		
		pd = new ProgressDialog(MyBrowser.this);
		final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
		
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setDomStorageEnabled( true );
		webView.getSettings().setAllowFileAccess( true );
		//webView.getSettings().setAllowFileAccessFromFileURLs( true );
		webView.getSettings().setPluginsEnabled( true );
		webView.setWebViewClient(new WebViewClient(){
			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				text.setText(url);
				super.onPageStarted(view, url, favicon);
			}
			
			/*
			
			public void onLoadResource(WebView view, String url) {
				Log.d("browser on load ", url );
				
		    }
			*/
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				Log.d("browser on override", url );
				if( url.endsWith("docx") || url.endsWith("pdf") ){
					final String download_url = url;
					alertDialog.setTitle("提示");
					alertDialog.setMessage("确认下载文件并打开?");
					alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
					    public void onClick(DialogInterface dialog, int which) {
					    	final String savePath = SystemConstant.FILE_DOWNLOAD_PATH + "abc" + download_url.substring( download_url.lastIndexOf(".") );
							//ProgressDialog pd = new ProgressDialog(MyBrowser.this);
							Runnable runnable = new Runnable(){
								@Override
								public void run() {
									Log.d("browser down file", "===end===");
									//String packageName = "cn.wps.moffice_eng";
									//String activityName = "cn.wps.moffice.documentmanager.PreStartActivity";
									//PackageUtil.openFileByDesignatedApp(MyBrowser.this, new File(savePath), packageName, activityName);
									WPSAssistant.openFile( MyBrowser.this, new File(savePath), true );
								}						
							};
							DownloadAsynTask.downloadSingleFile(download_url, savePath, pd, runnable);
					    }
					});
					alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
					    public void onClick(DialogInterface dialog, int which) {
					        alertDialog.dismiss();
					    }
					});
					alertDialog.show();
					
				}else{
					view.loadUrl(url);
				}				
		        return true;
		    }
		});
		webView.setWebChromeClient(new WebChromeClient(){
			@Override
			public boolean onJsAlert(WebView view, String url, String message,
					final JsResult result) {
				AlertDialog.Builder b = new AlertDialog.Builder(MyBrowser.this);
				b.setTitle("Alert");
				b.setMessage(message);
				b.setPositiveButton(android.R.string.ok,
						new AlertDialog.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								result.confirm();
							}
						});
				b.setCancelable(false);
				b.create();
				b.show();
				return true;
			};

			@Override
			public boolean onJsConfirm(WebView view, String url, String message,
					final JsResult result) {
				AlertDialog.Builder b = new AlertDialog.Builder(MyBrowser.this);
				b.setTitle("Confirm");
				b.setMessage(message);
				b.setPositiveButton(android.R.string.ok,
						new AlertDialog.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								result.confirm();
							}
						});
				b.setNegativeButton(android.R.string.cancel,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								result.cancel();
							}
						});
				b.setCancelable(false);
				b.create();
				b.show();
				return true;
			};

			@Override
			public boolean onJsPrompt(WebView view, String url, String message,
					String defaultValue, final JsPromptResult result) {
				final LayoutInflater factory = LayoutInflater.from(MyBrowser.this);
				final View v = factory.inflate(R.layout.javascript_prompt_dialog, null);
				((TextView) v.findViewById(R.id.prompt_message_text)).setText(message);
				((EditText) v.findViewById(R.id.prompt_input_field))
						.setText(defaultValue);

				AlertDialog.Builder b = new AlertDialog.Builder(MyBrowser.this);
				b.setTitle("Prompt");
				b.setView(v);
				b.setPositiveButton(android.R.string.ok,
						new AlertDialog.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								String value = ((EditText) v.findViewById(R.id.prompt_input_field)).getText().toString();
								result.confirm(value);
							}
						});
				b.setNegativeButton(android.R.string.cancel,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								result.cancel();
							}
						});
				b.setOnCancelListener(new DialogInterface.OnCancelListener() {
							public void onCancel(DialogInterface dialog) {
								result.cancel();
							}
						});
				b.show();
				return true;
			};

			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				MyBrowser.this.getWindow().setFeatureInt(Window.FEATURE_PROGRESS, newProgress * 100);
				super.onProgressChanged(view, newProgress);
			}

			@Override
			public void onReceivedTitle(WebView view, String title) {
				MyBrowser.this.setTitle(title);
				super.onReceivedTitle(view, title);
			}
		});
		go.setOnClickListener(new OnClickListener(){
			public void onClick(View view) {
				String url=text.getText().toString();
				webView.loadUrl(url);
			}
		});
		
		webView.loadUrl("file:///android_asset/index.html");
	}
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		WebView mWebView=(WebView)findViewById(R.id.browser);
		if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
			mWebView.goBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
    protected void onStart(){
    	Log.d(TAG, "register broadcast receiver ");
    	/*
    	dsReceiver = new DocSaveReceiver();
    	IntentFilter filter = new IntentFilter();
    	filter.addAction("cn.wps.moffice.file.save");
    	//filter.addAction("hoyi.locate_emp.jczx");
    	this.registerReceiver(dsReceiver, filter); */
    	super.onStart();
    }
    
    @Override
    protected void onDestroy(){
    	//this.unregisterReceiver( dsReceiver );
    	//dsReceiver = null;
    	super.onDestroy();
    }
}
